package com.lfb.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientThread implements Runnable{
	/**
	 *服务器主机的IP地址
	 */
	private String hostIp;
	/*
	 * 服务 器主机socket通信监听的端口号
	 * 客户端与服务器端所指定的端口号要一致
	 */
	private int port;
	
	
	public ClientThread(String hostIp, int port) {
		super();
		this.hostIp = hostIp;
		this.port = port;
	}


	@Override
	public void run() {
		try {
			/************客户端使用输出流发送消息*********/
			//创建一个socket客户端对象
			Socket socket = new Socket(hostIp,port);
			//获取客户端输出流 对象
			BufferedWriter  bw= new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "utf-8"));
			//客户端发送的消息
			String 	strM_c	= "你好，我是客户端";
			//将消息数据流通过网络发送出去
			bw.write(strM_c+"\n");
			//write没有行结束符，单独写行结束符
			bw.write("又一次来自客户端的消息\n");
			
			//发送消息结束符
			bw.write("eof\n");
			//清空缓存
			bw.flush();
			//输出信息
			System.out.println("客户端发送消息" + strM_c);
			//关闭资源
			//bw.close();
			
			
			
			/****客户端使用输入流接收服务器端发送的信息****/
			BufferedReader br =  new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
			//读入服务器端信息
			String strM_s = br.readLine();
			while (strM_s != null && !strM_s.equals("eof")) {
				//输出信息
				System.out.println("客户端接收信息:" + strM_s);
				strM_s = br.readLine();
			}

			//关闭资源--断开连接
			//br.close();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
}
